package com.party.admin.task;

import com.google.common.collect.Lists;
import com.party.admin.biz.file.ExcelExportService;
import com.party.common.constant.Constant;
import com.party.common.utils.DateUtils;
import com.party.core.service.picCloud.CosCloudBizService;
import com.party.file.cos.dto.UploadResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * 定时删除腾讯云excel文件
 * Created by wei.li
 *
 * @date 2017/4/12 0012
 * @time 19:48
 */
@Component(value = "quartzDeleteCloudExcel")
public class QuartzDeleteCloudExcel {

    @Autowired
    private ExcelExportService excelExportService;

    @Autowired
    private CosCloudBizService cosCloudBizService;

    public void deleteYesterdayExcel() {
        List<Map> mapList = excelExportService.getRedisAll();
        List<Map> newMapList = Lists.newArrayList();
        for (Map map : mapList) {
            map.forEach((key, value) -> {
                String today = DateUtils.formatDate(new Date(), DateUtils.DATE_PATTERN);
                if (!value.equals(today)) {
                    try {
                        if (null == key) {
                            newMapList.add(map);
                        } else {
                            String resourceUrl = key.toString();
                            if (resourceUrl.indexOf(Constant.BATCH) != -1) {
                                resourceUrl = "/" + resourceUrl.substring(resourceUrl.indexOf(Constant.BATCH), resourceUrl.length());
                            }
                            UploadResult deleteResult = cosCloudBizService.deleteFile(resourceUrl);
                            if ((deleteResult.getCode() == 0 && deleteResult.getMessage().equals("SUCCESS")) || deleteResult.getCode() == -197) {
                                newMapList.add(map);
                            }
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            });
        }
        mapList.removeAll(newMapList);
        excelExportService.pushRedis(mapList);
    }
}
